<template>
  <a-modal
    title="编辑工单表"
    width="80%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item v-show="false"><a-input v-decorator="['id']" /></a-form-item>
        <a-form-item v-show="false"><a-input v-decorator="['factStaTime']" /></a-form-item>
        <a-form-item v-show="false"><a-input v-decorator="['factEndTime']" /></a-form-item>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item
              label="工单编号"
              readOnly
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-input readOnly placeholder="请输入工单编号" v-decorator="['workOrderNo']"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="产品"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <pro-select
                placeholder="请选择产品"
                v-decorator="['proId', { rules: [{ message: '请选择产品！' }]}]"
                @change="proChange"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item
              label="计划时间"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-range-picker
                v-decorator="['plaTime', {rules: [{required: true, message: '请选择计划时间！'}]}]"
                :show-time="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始时间', '结束时间']"
                style="width: 100%"
                @change="plaTimeOnChange"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="计划数"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-input-number
                @change="plaNumChange"
                style="width: 100%"
                placeholder="请输入计划数"
                v-decorator="['plaNum', {rules: [{required: true, message: '请输入计划数！'}]}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item
              label="下单人"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <user-select
                placeholder="请选择下单人"
                v-decorator="['nextPerson', { rules: [{ message: '请选择下单人！' }]}]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="下单时间"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-date-picker
                style="width: 100%"
                :show-time="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                placeholder="请选择下单时间"
                v-decorator="['orderTime']"
                @change="orderTimeOnChange"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item
              label="负责人"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <user-select
                placeholder="请选择负责人"
                v-decorator="['personCharge', { rules: [{ message: '请选择负责人！' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <custom-upload
              ref="enclosure"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :isDisabled="false"
              labelName="附件"
              colName="enclosure"
              :rules="[{required: false, message: ''}]"
            />
          </a-col>
        </a-row>
        <task-table-form-item
          ref="child"
          :oldTableData="taskList"
          :badItemList="list.badItem"
          :plaNum="form.getFieldValue('plaNum')?form.getFieldValue('plaNum'):null"
          :plaStartTime="plaTimeString && plaTimeString.length >= 1?plaTimeString.split(';')[0]:null"
          :plaEndTime="plaTimeString && plaTimeString.length >= 2?plaTimeString.split(';')[1]:null"
          @tableDataChange="(data)=>{taskList = data}"
        />

        <a-form-item
          label="备注信息"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-textarea :rows="3" placeholder="请输入备注信息" v-decorator="['remarks']" />
        </a-form-item>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import moment from 'moment'
import { workOrderEdit } from '@/api/modular/main/workorder/workOrderManage'
import { proList } from '@/api/modular/main/pro/proManage'
import taskTableFormItem from '@/views/main/workorder/taskTableFormItem'
import ProSelect from '@/components/MyComp/ProSelect'
import { workStepRouteList } from '@/api/modular/main/worksteproute/workStepRouteManage'
import { workRouteList } from '@/api/modular/main/workroute/workRouteManage'
import { workStepList } from '@/api/modular/main/workstep/workStepManage'
import UserSelect from '@/components/MyComp/UserSelect'
import CustomUpload from '@/components/MyComp/CustomUpload'
export default {
  components: {
    UserSelect,
    ProSelect,
    taskTableFormItem,
    CustomUpload
  },
  data () {
    return {
      orderTimeDateString: [],
      taskList: [],
      initEdit: {
        proId: '',
        isInitProIdChange: false
      },
      allWorkRouteStepList: [],
      allWorkRouteList: [],
      allWorkStepList: [],
      list: {
        pro: [],
        badItem: []
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },

      labelCol_T: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol_T: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      plaTimeString: '',
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this)
    }
  },
  methods: {
    moment,
    // 初始化方法
    edit (record) {
      // 取附件中的数据
      // this.$refs.enclosure.setFileList(record.enclosure)
      this.visible = true
      // 调用api方法
      proList().then(res => {
        this.list.pro = res.data
      })
      this.list.badItem = this.$options.filters['dictData']('bad_item')
      //  获取工艺路线关系列表
      workStepRouteList().then(res => {
        this.allWorkRouteStepList = res.data || []
      })
      // 获取工艺路线列表
      workRouteList().then(res => {
        this.allWorkRouteList = res.data || []
      })
      // 获取工序列表
      workStepList().then(res => {
        this.allWorkStepList = res.data || []
      })
      // 保存初始化产品id数据
      this.initEdit.proId = record.proId
      this.initEdit.isInitProIdChange = !this.initEdit.isInitProIdChange

      if (!this.$utils.isEmpty(record.taskList)) {
        this.taskList = [...record.taskList]
        this.taskList.forEach(item => {
          if (!this.$utils.isEmpty(item.reportRight) && this.$utils.isString(item.reportRight)) {
            item.reportRight = item.reportRight.split(';')
          }
        })
      }

      this.$nextTick(() => {
        this.$refs.enclosure.setFileList(record.enclosure)
        // 取附件中的数据
        // this.$refs.enclosure.setFileList(record.enclosure)
        this.form.setFieldsValue(
          {
            factEndTime: record.factEndTime,
            factStaTime: record.factStaTime,
            id: record.id, // 工单id
            plaNum: record.plaNum,
            proId: record.proId,
            remarks: record.remarks,
            workOrderNo: record.workOrderNo,
            nextPerson: record.nextPerson,
            personCharge: record.personCharge
          }
        )
      })

      // 时间单独处理
      if (record.plaStartTime && record.plaEndTime) {
        this.form.getFieldDecorator('plaTime', { initialValue: [moment(record.plaStartTime, 'YYYY-MM-DD HH:mm'), moment(record.plaEndTime, 'YYYY-MM-DD HH:mm')] })
        this.plaTimeString = [moment(record.plaStartTime).format('YYYY-MM-DD HH:mm'), moment(record.plaEndTime).format('YYYY-MM-DD HH:mm')].join(';')
      }
      if (record.orderTime) {
        this.form.getFieldDecorator('orderTime', { initialValue: moment(record.orderTime, 'YYYY-MM-DD HH:mm') })
        this.orderTimeDateString = moment(record.orderTime).format('YYYY-MM-DD HH:mm')
      }
    },
    // 修改产品选择
    proChange (val) {
      // 点击编辑页面初始化时会自动执行该change方法
      // 判断是否为第一次初始化时修改的proId，若为初始化时的数据回显值，taskList不变
      if (val === this.initEdit.proId && this.initEdit.isInitProIdChange) {
        this.initEdit.isInitProIdChange = !this.initEdit.isInitProIdChange // 修改初始化状态，下次点击到与初始化proId相同的值时，正常加载与该产品id对应的工序列表
        return
      }
      let workRouteId = ''
      let workRSData = {}
      const stepRoutList = []
      this.list.pro.forEach(pro => {
        if (pro.id === val) {
          workRouteId = pro.workRouteId
          if (!workRouteId || !this.allWorkRouteList) {
            this.$message.warn('该产品未绑定工艺路线，请手动添加工序')
            return
          }
          // 获取产品id对应的工艺路线
          this.allWorkRouteList.forEach(route => {
            if (route.id === workRouteId) {
              workRSData = route || {}
            }
          })
          // 获取对应的工艺路线与工序关系列表
          this.allWorkRouteStepList.forEach(item => {
            if (item.workRouteId === workRouteId) {
              const stepRoute = item
              this.allWorkStepList.forEach(step => {
                if (step.id === item.workStepId) {
                  stepRoute['mulBadItem'] = step.mulBadItem
                }
              })
              stepRoutList.push(stepRoute)
            }
          })
          if (stepRoutList && stepRoutList.length > 0) {
            workRSData['workStepRouteList'] = stepRoutList
          }
        }
      })
      this.$refs.child.handleWorkRouteConfirm(workRSData)
    },
    handleSubmit () {
      this.form.setFieldsValue({
        enclosure: this.$refs.enclosure.getFileList()
      })
      const { form: { validateFields } } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          for (const key in values) {
            if (typeof (values[key]) === 'object' && values[key] != null) {
              values[key] = JSON.stringify(values[key])
            }
          }
          values.orderTime = this.orderTimeDateString || null
          values.plaTime = this.plaTimeString || null
          values.taskList = [...this.taskList]
          values.taskList.forEach((element, index) => {
            element.sortNum = index + 1
            if (!this.$utils.isEmpty(element.reportRight)) {
              element.reportRight = element.reportRight.join(';')
            }

            if (!this.$utils.isEmpty(element.mulBadItem) && typeof element.mulBadItem === 'object') {
              element.mulBadItem = element.mulBadItem.join(';')
            }
          })
          workOrderEdit(values).then((res) => {
            if (res.success) {
              this.$message.success('编辑成功')
              this.confirmLoading = false
              this.$emit('ok', values)
              this.handleCancel()
            } else {
              this.$message.error('编辑失败：' + res.message)
            }
          }).finally((res) => {
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    plaTimeOnChange(date, dateStrArr) {
      this.plaTimeString = dateStrArr.join(';')
      this.taskList.forEach(item => {
        item.plaStartTime = dateStrArr[0]
        item.plaStartTime = dateStrArr[1]
      })
    },
    plaNumChange(val) {
      this.taskList.forEach(item => {
        item.plaNum = val
      })
    },
    orderTimeOnChange(date, dateString) {
      this.orderTimeDateString = dateString
      this.form.setFieldsValue({
        orderTime: moment()
      })
    },
    handleCancel () {
      // 取消是文件要单独置空
      this.$refs.enclosure.setFileList(null)
      this.taskList = []
      this.plaTimeString = ''
      this.form.getFieldDecorator('plaTimeString', { initialValue: null })
      this.form.resetFields()
      this.visible = false
      this.initEdit.isInitProIdChange = false
      this.$emit('ok')
    }
  }
}
</script>
